<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" size="small" :model="queryParams" class="demo-form-inline"
             v-hasPermi="['res:project:query']">
      <el-form-item label="项目名称" prop="name">
        <el-input v-model.trim="queryParams.name" :maxlength="50" placeholder="请输入项目名称"/>
      </el-form-item>
      <el-form-item label="项目级别" prop="level">
        <el-select v-model="queryParams.level" clearable placeholder="请选择项目级别" default-first-option filterable
                   style="width: 100%;">
          <el-option v-for="item in dict.type.sys_research_project_level" :key="item.value" :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择状态"
                   default-first-option filterable style="width: 100%;">
          <el-option v-for="item in dict.type.sys_develop_project_status" :key="item.value" :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['res:project:add']"
                     @click="openDialog(null)">增加
          </el-button>
          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['res:project:export']"
                     @click="exportHandler">导出
          </el-button>
        </div>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableData"
      highlight-current-row
      max-height="680"
      v-loading="loading"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      />
      <el-table-column
        property="name"
        label="项目名称"
        align="center"
        min-width="120"
      />
      <el-table-column
        property="source"
        label="项目来源"
        align="center"
      />
      <el-table-column
        property="level"
        label="项目级别"
        align="center"
      />
      <el-table-column
        property="supervisoryUnit"
        label="归口单位"
        align="center"
      />
      <el-table-column
        property="applyDate"
        label="申请日期"
        align="center"
        min-width="90"
      />
      <el-table-column
        property="applicationUnit"
        label="申报单位"
        align="center"
        min-width="140"
      />
      <el-table-column
        property="participant"
        label="参与人"
        align="center"
        min-width="90"
      />
      <el-table-column
        property="personnelForCommunicating"
        label="司外对接人"
        align="center"
        min-width="90"
      />
      <el-table-column
        property="status"
        label="状态"
        align="center"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_develop_project_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column
        property="checkDate"
        label="验收日期"
        align="center"
      />
      <el-table-column
        property="subsidyAmount"
        label="补贴金额(万元)"
        align="center"
        min-width="110"
      />
      <el-table-column
        property="arrivalAmount"
        label="到款金额(万元)"
        align="center"
        min-width="110"
      />
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        min-width="140"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('res:project:edit') || $auth.hasPermi('res:project:remove') || $auth.hasPermi('res:project:view')"
      >
        <template slot-scope="scope">
          <el-dropdown @command="(val) => handleFileCommand(val, scope.row)"
                       v-if="(scope.row.publicNotice || scope.row.bankReceiveBill) && $auth.hasPermi('res:project:view')">
            <span class="el-dropdown-link">
              <el-button type="text" icon="el-icon-view">查看附件</el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="0" v-if="scope.row.publicNotice">公示文件</el-dropdown-item>
              <el-dropdown-item :command="1" v-if="scope.row.bankReceiveBill">银行收款单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['res:project:edit']" @click="openDialog(scope.row)">
            修改
          </el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['res:project:remove']" type="text"
                       style="margin-left: 10px">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
      :fullscreen="device === 'mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form"
               :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model.trim="form.name" :maxlength="50" placeholder="请输入项目名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目来源" prop="source">
              <el-input v-model.trim="form.source" :maxlength="20" placeholder="请输入项目来源"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目级别" prop="level">
              <el-select v-model="form.level" clearable placeholder="请选择项目级别" default-first-option filterable
                         style="width: 100%;">
                <el-option v-for="item in dict.type.sys_research_project_level" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="归口单位" prop="supervisoryUnit">
              <el-input v-model.trim="form.supervisoryUnit" :maxlength="50" placeholder="请输入归口单位"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="申请日期">
              <el-date-picker
                v-model="form.applyDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="申报单位" prop="applicationUnit">
              <el-select v-model="form.applicationUnit" clearable placeholder="请选择项目申报单位" multiple allow-create
                         default-first-option filterable style="width: 100%;">
                <!--                <el-option v-for="item in []" :key="item.value" :label="item.label" :value="item.value"/>-->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="参与人" prop="participant">
              <el-select v-model="form.participant" clearable placeholder="请选择项目参与人员" multiple allow-create
                         default-first-option filterable style="width: 100%;">
                <!--                <el-option v-for="item in []" :key="item.value" :label="item.label" :value="item.value"/>-->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="司外对接人" prop="personnelForCommunicating">
              <el-select v-model="form.personnelForCommunicating" clearable placeholder="请选择司外对接人员" multiple
                         allow-create default-first-option filterable style="width: 100%;">
                <!--                <el-option v-for="item in []" :key="item.value" :label="item.label" :value="item.value"/>-->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" clearable placeholder="请选择状态"
                         default-first-option filterable style="width: 100%;">
                <el-option v-for="item in dict.type.sys_develop_project_status" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="验收日期" prop="checkDate">
              <el-date-picker
                v-model="form.checkDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="补贴金额" prop="subsidyAmount">
              <el-input v-model.trim="form.subsidyAmount" :maxlength="20" placeholder="请输入补贴金额">
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="到款金额" prop="arrivalAmount">
              <el-input v-model.trim="form.arrivalAmount" :maxlength="20" placeholder="请输入到款金额">
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="公示文件" prop="publicNotice">
              <el-upload class="upload-demo1" ref="upload2" action="#" :limit="1" :on-change="handleChange2"
                         :on-remove="handleRemove2" :file-list="fileList2" :auto-upload="false"
                         accept=".pdf"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="银行收款账单" prop="bankReceiveBill">
              <el-upload class="upload-demo2" ref="upload2" action="#" :limit="1" :on-change="handleChange1"
                         :on-remove="handleRemove1" :file-list="fileList1" :auto-upload="false"
                         accept=".pdf"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" :maxlength="200"
                    placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="uploadLoading" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/saas/research/project/declare";
import {getUserProfile} from "@/api/system/user";
import {mapGetters} from 'vuex'
import {uploadImgApi} from "@/api/after/serve";
import {isFileOfType} from "@/utils";

export default {
  name: 'ResearchDeclare',
  dicts: ['sys_research_project_level', 'sys_develop_project_status'],
  data() {
    return {
      uploadLoading: false, // 上传动画
      env: process.env.VUE_APP_STATIC_API || "",
      fileList1: [],
      fileList2: [],
      // 加载动画
      loading: true,
      // 活动日期
      activityDate: [],
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        checkDate: "", // 验收时间
        type: 1,
        supervisoryUnit: "", // 归口单位*
        applyDate: "", // 项目申请时间*
        applicationUnit: [], // 项目申报单位* 多选
        participant: [], // 项目参与人员* 多选
        personnelForCommunicating: [], // 司外对接人员 多选
        status: "", // 状态*
        name: "", // 项目名称 *
        source: "", // 项目来源 *
        level: "", // 项目级别 *
        subsidyAmount: "", // 补贴金额 *
        arrivalAmount: "", // 到账金额 *
        publicNotice: "", // 公示文件 *
        bankReceiveBill: "", // 银行收款单 *
        createBy: "", // 创建人 *
        createTime: "", // 创建时间 *
        id: null, // id
        remark: "", // 备注
        updateBy: "", // 更新时间
        updateTime: "", // 更新人
      },
      // 表单的校验规则
      rules: {
        name: [
          {required: true, message: '请填写项目名称', trigger: 'blur'}
        ],
        source: [
          {required: true, message: '请填写项目来源', trigger: 'blur'}
        ],
        level: [
          {required: true, message: '请选择项目级别', trigger: 'change'}
        ],
        supervisoryUnit: [
          {required: true, message: '请填写归口单位', trigger: 'blur'}
        ],
        applyDate: [
          {required: true, message: '请选择项目申请时间', trigger: 'change'}
        ],
        applicationUnit: [
          {required: true, message: '请选择项目申报单位', trigger: 'change'}
        ],
        participant: [
          {required: true, message: '请选择项目参与人员', trigger: 'change'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'change'}
        ]
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        type: 1,
        status: "",
        name: "",
        level: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
    }
  },
  watch: {
    activityDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  created() {
    this.getList()
    this.getUserinfo()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 查看附件
    handleFileCommand(isPerformance, row) {
      if (isPerformance === 0) {
        this.handleView(row.publicNotice)
      } else if (isPerformance === 1) {
        this.handleView(row.bankReceiveBill)
      }
    },
    // 查看合同
    handleView(url) {
      window.open(this.env + url)
    },
    // 上传全部图片
    async uploadImg(fileList = [], cb = () => {
    }) {
      if (fileList.length <= 0) {
        cb && cb("")
        return false
      }

      const urlList = (fileList ?? []).filter(i => !i.raw).map(i => i.url)

      if (urlList && urlList[0]) return false

      if (fileList.length <= 0) {
        this.form.certification = ""
        return false
      }

      const file = fileList[0]
      const formData = new FormData()
      formData.append('file', file.raw)
      const {fileName} = await uploadImgApi(formData)

      cb && cb(fileName)
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 选中图片
    handleChange2(_, fileList) {

      const file = fileList[0] ?? null

      if (isFileOfType(file.name, ['.pdf'])) {
        this.fileList2 = fileList
      } else {
        this.$notify.error({
          title: '错误',
          message: '文件选择错误'
        });
        this.fileList2 = []
      }
    },
    // 删除图片
    handleRemove2(_, fileList) {
      this.fileList2 = fileList
    },
    // 选中图片
    handleChange1(_, fileList) {
      const file = fileList[0] ?? null

      if (isFileOfType(file.name, ['.pdf'])) {
        this.fileList1 = fileList
      } else {
        this.$notify.error({
          title: '错误',
          message: '文件选择错误'
        });
        this.fileList1 = []
      }
    },
    // 删除图片
    handleRemove1(_, fileList) {
      this.fileList1 = fileList
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.fileList2 = ((row.publicNotice ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: this.env + item
        }))
        this.fileList1 = ((row.bankReceiveBill ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: this.env + item
        }))
        this.form = {
          ...row,
          applicationUnit: row.applicationUnit?.split(',')?.filter(i => i) ?? [],
          participant: row.participant?.split(',')?.filter(i => i) ?? [],
          personnelForCommunicating: row.personnelForCommunicating?.split(',')?.filter(i => i) ?? []
        }
        this.dialogTitle = 2
      } else {
        this.fileList1 = []
        this.fileList2 = []
        this.form = {...this.$options.data().form}
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.resetForm('formRef')
    },
    // 导出的回调
    async exportHandler() {
      this.download('saas/researchProject/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `researchProjects_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if(this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      const _this = this

      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            this.uploadLoading = true
            await this.uploadImg(this.fileList2, (fileListStr) => {
              // console.log(fileListStr)
              _this.form.publicNotice = fileListStr
            })

            await this.uploadImg(this.fileList1, (fileListStr) => {
              _this.form.bankReceiveBill = fileListStr
            })
          } catch (error) {
            this.uploadLoading = false
          }

          this.uploadLoading = false

          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        applicationUnit: this.form.applicationUnit.join(','),
        participant: this.form.participant.join(','),
        personnelForCommunicating: this.form.personnelForCommunicating.join(','),
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        applicationUnit: this.form.applicationUnit.join(','),
        participant: this.form.participant.join(','),
        personnelForCommunicating: this.form.personnelForCommunicating.join(','),
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.activityDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">

</style>
